package com.paomi.client.fragment.first;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.paomi.client.GlideApp;
import com.paomi.client.R;
import com.paomi.client.activity.classify.SearchClassifyActivity;
import com.paomi.client.activity.newsDetail.NewsDetailActivity;
import com.paomi.client.activity.person.model.TaskListBean;
import com.paomi.client.activity.person.model.TaskListDetailBean;
import com.paomi.client.activity.search.SearchActivity;
import com.paomi.client.base.BaseLCEFragment;
import com.paomi.client.bean.UserUtils;
import com.paomi.client.fragment.first.adapter.FirstListAdapter;
import com.paomi.client.fragment.first.adapter.TopAdapter;
import com.paomi.client.fragment.first.model.ListTopJson;
import com.paomi.client.fragment.first.model.NewsJson;
import com.paomi.client.activity.newsDetail.model.NewsListJson;
import com.paomi.client.fragment.first.model.TicketJson;
import com.paomi.client.fragment.first.model.TicketListJson;
import com.paomi.client.fragment.first.presenter.FirstFraPre;
import com.paomi.client.utils.ToastUtil;
import com.paomi.client.utils.UIUtils;
import com.paomi.client.utils.Util;
import com.paomi.client.view.HorizontalBanner;
import com.paomi.client.view.HorizontalNewBanner;
import com.paomi.client.view.LoadingDialog;
import com.paomi.client.view.MyGridLayoutManager;
import com.paomi.client.view.SignInDialog;
import com.paomi.client.widget.header.HeaderGetView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by pc on 2018/10/25
 * Describe:首页
 * com.paomi.client.fragment
 */
public class FirstFragment extends BaseLCEFragment<NewsListJson, FirstFraPre> implements TopAdapter.ClickListener {


    @BindView(R.id.textview_title)
    TextView textviewTitle;
    @BindView(R.id.nes_scroll)
    NestedScrollView nes_scroll;
    @BindView(R.id.first_banner)
    HorizontalBanner firstBanner;
    @BindView(R.id.x_banner)
    HorizontalNewBanner x_banner;
    @BindView(R.id.video_iv)
    ImageView videoIv;
    @BindView(R.id.video_num)
    TextView videoNum;
    @BindView(R.id.msg_iv)
    ImageView msgIv;
    @BindView(R.id.msg_num)
    TextView msgNum;
    @BindView(R.id.angry_iv)
    ImageView angryIv;
    @BindView(R.id.angry_num)
    TextView angryNum;
    @BindView(R.id.card_iv)
    ImageView cardIv;
    @BindView(R.id.card_num)
    TextView cardNum;
    @BindView(R.id.recycler_view_top)
    RecyclerView recycler_view_top;
    @BindView(R.id.lv_ticket)
    RecyclerView lv_ticket;
    @BindView(R.id.lv_news)
    RecyclerView lv_news;
    @BindView(R.id.tv_search_icon)
    TextView tvSearchIcon;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_search_clear)
    TextView tvSearchClear;
    @BindView(R.id.go_search)
    LinearLayout goSearch;
    @BindView(R.id.ptr_main)
    PtrClassicFrameLayout ptrMain;
    @BindView(R.id.iv_sign)
    ImageView iv_sign;
    @BindView(R.id.null_net)
    RelativeLayout null_net;
    private TopAdapter topadapter;
    private List<ListTopJson> listTopJsons = new ArrayList<>();
    private FirstListAdapter firstadapter;//售票列表的适配
    //    @BindView(R.id.list_tab_pager)
//    MyPagerSlidingTabStrip listTabPager;
//    @BindView(R.id.list_found_pager)
//    ViewPager listFoundPager;
    private SignInDialog dialog;
    private List<NewsListJson> newsJsonList = new ArrayList();
    //    private BindPagerAdapter bindAdapter;
    private int pageN = 1;//热门资讯页码
    private int pageNume = 1;//精彩演出页码
    private List<TicketJson> ticketJsonList = new ArrayList();

    public static FirstFragment newInstance(String name) {

        Bundle args = new Bundle();
        args.putString("name", name);
        FirstFragment fragment = new FirstFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @NonNull
    @Override
    protected int getFragmentLayoutId() {
        return R.layout.fragment_first;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        textviewTitle.setText(getResources().getString(R.string.title_home));
        tvSearchIcon.setTypeface(iconfont);
        tvSearchClear.setTypeface(iconfont);
        firstBanner.setNestedpParent(ptrMain);
        x_banner.setNestedpParent(ptrMain);
//        Util.setWidthAndHeight(firstBanner, -1, (int) (Util.getDisplay(getActivity()).widthPixels*0.467));
        Util.setWidthAndHeight(x_banner, -1, (int) (Util.getDisplay(getActivity()).widthPixels*0.467));
        recycler_view_top.setLayoutManager(UIUtils.getRecyclerViewManager(true, getActivity()));
        //设置适配器
        topadapter = new TopAdapter(getActivity(), this);
        recycler_view_top.setAdapter(topadapter);

        listTopJsons.clear();
        ListTopJson top1 = new ListTopJson();
        top1.setType_name("精彩演出");
        top1.setType(1);
        ListTopJson top2 = new ListTopJson();
        top2.setType_name("热门资讯");
        listTopJsons.add(top1);
        listTopJsons.add(top2);
        topadapter.setdata(listTopJsons);


        MyGridLayoutManager gridLayoutManager = new MyGridLayoutManager(getActivity(), 2);
        gridLayoutManager.setScrollEnabled(false);
        lv_ticket.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        lv_ticket.setLayoutManager(gridLayoutManager);
        // 设置为 true
        lv_ticket.setHasFixedSize(true);
        lv_ticket.setItemAnimator(new DefaultItemAnimator());
        // 设置为 false
        lv_ticket.setNestedScrollingEnabled(false);// 解决滑动冲突
        lv_news.setNestedScrollingEnabled(false);// 解决滑动冲突
        firstadapter = new FirstListAdapter(getActivity());
        lv_ticket.setAdapter(firstadapter);
        if(getNetworkType()==0){//判断是否有网
            null_net.setVisibility(View.VISIBLE);
        }else{
            null_net.setVisibility(View.GONE);
            getPresenter().setBannerList(firstBanner, getActivity(),x_banner);
        }


//        dialog = new SignInDialog(getActivity()).creatDialog();
//        listTabPager.setSelected(true);
//        bindAdapter = new BindPagerAdapter(getActivity().getSupportFragmentManager(), arrayList);
//        listFoundPager.setAdapter(bindAdapter);
//        listTabPager.setViewPager(listFoundPager);
//        listFoundPager.setCurrentItem(0);
        //添加下拉刷新
        setPtrFrameLayout(ptrMain);
        HeaderGetView header=new HeaderGetView(getActivity());
        ptrMain.setHeaderView(header);
        ptrMain.addPtrUIHandler(header);
        ptrMain.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view2) {
                return nes_scroll.getScrollY() == 0;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                getPresenter().setBannerList(firstBanner, getActivity(),x_banner);
                if(getNetworkType()==0){//判断是否有网
                    null_net.setVisibility(View.VISIBLE);
                }else{
                    null_net.setVisibility(View.GONE);
                }
            }
        });

    }

    /**
     * 分类顶部的单项点击事件
     *
     * @param smart
     */
    @Override
    public void clickTopListener(ListTopJson smart) {
        if (smart.getType_name().equals("精彩演出")) {
//            getPresenter().setTicketJsonList("1");
            lv_ticket.setVisibility(View.VISIBLE);
            lv_news.setVisibility(View.GONE);
        } else {
//            getPresenter().setLoadNewsData(pageN);
            lv_ticket.setVisibility(View.GONE);
            lv_news.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        x_banner.startAutoPlay();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (UserUtils.getInstance().getUserInfo1() != null) {
            getPresenter().getTaskList();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        x_banner.stopAutoPlay();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 资讯列表成功后返回的信息
     *
     * @param result
     */
    @Subscribe
    public void onEvent(NewsJson result) {
        Log.e("resultNes", "" + result.getReturnData().getData().size());
        if (result.getReturnData().getData().size() > 0) {
            if (pageN == 1) {
                newsJsonList.clear();
            }
            newsJsonList.addAll(result.getReturnData().getData());
        }
        setData(newsJsonList, true);
    }

    /**
     * 售票列表成功后返回的信息
     *
     * @param result
     */
    @Subscribe
    public void onEvent(TicketListJson.TicketList result) {
        Log.e("resultTicket", "" + result.getData().size());
        if (pageNume == 1) {
            ticketJsonList.clear();
        }
        ticketJsonList.addAll(result.getData());
        firstadapter.setData(ticketJsonList);
    }

    @Subscribe
    public void onEvent(Object result) {
        if (result instanceof TaskListBean) {
            if (((TaskListBean) result).returnCode.equals("0000")) {
                List<TaskListDetailBean> list = new ArrayList<>();
                list.addAll(((TaskListBean) result).getReturnData());
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getName().contains("签到")) {
                        if (list.get(i).isComplete()) {
                            iv_sign.setVisibility(View.GONE);
                        } else {
                            iv_sign.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        }
        if (result instanceof String) {
            if (result.equals("SignSuccess")) {
//                ToastUtil.getToastEmail().ToastSign(getActivity(), null, 1, R.layout.toast_sign, "+20");
                iv_sign.setVisibility(View.GONE);
                getPresenter().getSignDialog(getActivity());
            }
        }
    }

//    /**
//     *首页广告返回的数据
//     * @param result
//     */
//    @Subscribe
//    public void onEvent(BannerBean result) {
//
//    }

    @NonNull
    @Override
    protected RecyclerView createRecycler() {
        return lv_news;
    }

    @Override
    protected int getItemLayout() {
        return R.layout.item_news_list;
    }

    @Override
    protected void initEmpty(TextView empty) {
        empty.setText("数据为空");
    }

    @Override
    protected void convert(BaseViewHolder helper, NewsListJson item) {
        helper.setText(R.id.title_news, item.getName());
        helper.setText(R.id.site_news, item.getSource());
        RoundedImageView imageView = helper.itemView.findViewById(R.id.iv_news);
//        Util.setWidthAndHeight(imageView, -1, (int) (Util.getDisplay(getActivity()).widthPixels * 0.8));
        GlideApp.with(this).load(item.getImg_url()).placeholder(R.mipmap.img_default_msg).into(imageView);
    }

    @Override
    protected void onItemClick(View view, NewsListJson item) {
        Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
        intent.putExtra("newId", "" + item.getUri());
        startActivity(intent);
    }

    @Override
    public FirstFraPre createPresenter() {
        return new FirstFraPre();
    }

    @OnClick({R.id.go_search,R.id.et_search})
    public void onViewClicked() {
        getIntent(SearchActivity.class);
    }

    /**
     * 在无网的状态下重新加载
     */
    @OnClick(R.id.net_btn)
    void onNetClicked() {
        LoadingDialog.get().showLoading();
        getPresenter().setBannerList(firstBanner, getActivity(),x_banner);
        if(getNetworkType()==0){//判断是否有网
            null_net.setVisibility(View.VISIBLE);
            LoadingDialog.get().hideLoading();
        }else{
            null_net.setVisibility(View.GONE);
        }
    }

    @Override
    public void setData(List<NewsListJson> data, boolean pullToRefresh) {
        super.setData(data, pullToRefresh);
        //移除FooterView
        getmAdapterWrapper().setLoadItemVisibility(false);
    }

    @OnClick(R.id.iv_sign)
    void toSign() {
        getPresenter().toSign();
    }
}
